package com.reebake.ideal.user.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.reebake.ideal.holder.UserContextHolder;
import com.reebake.ideal.user.entity.UserCredential;
import com.reebake.ideal.user.service.UserAuthService;
import com.reebake.ideal.user.service.UserInfoService;
import com.reebake.ideal.user.vo.ResetPasswordVO;
import com.reebake.ideal.user.vo.UserRegisterVO;
import com.reebake.ideal.verify.code.core.VerifyCodeService;
import com.reebake.ideal.verify.code.entity.VerifyCodeEntity;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class UserAuthController {
    private final VerifyCodeService verifyCodeService;
    private final UserInfoService userInfoService;
    private final UserAuthService userAuthService;

    @PostMapping("/user/register")
    public Boolean register(@RequestBody @Valid UserRegisterVO userRegisterVO) {
        if(StrUtil.isNotBlank(userRegisterVO.getPhoneNumber())) {
            userAuthService.registerByPhoneNumber(userRegisterVO.getPhoneNumber(), userRegisterVO.getVerifyCode());
        }else if(StrUtil.isNotBlank(userRegisterVO.getUsername())) {
            userAuthService.registerByUsername(userRegisterVO.getUsername(), userRegisterVO.getPassword());
        }else if(StrUtil.isNotBlank(userRegisterVO.getEmail())) {
            userAuthService.registerByEmail(userRegisterVO.getEmail(), userRegisterVO.getVerifyCode());
        }else {
            throw new UnsupportedOperationException();
        }
        return true;
    }

    @Operation(description = "向自己发送验证码")
    @PostMapping("/user/verify-code/send-me")
    public void verifyCodeToMe() {
        String userId = UserContextHolder.getCurrentUserId();
        UserCredential userCredential = userAuthService.queryByUserId(userId);
        String phoneNumber = userCredential.getPhoneNumber();
        Assert.notBlank(phoneNumber);
        VerifyCodeEntity verifyCodeEntity = new VerifyCodeEntity();
        verifyCodeEntity.setReceiver(phoneNumber);
        verifyCodeService.save(verifyCodeEntity);
    }
    
    @PostMapping("/user/reset-password")
    public void resetPassword(@RequestBody @Valid ResetPasswordVO resetPasswordVO) {
        userAuthService.resetPassword(resetPasswordVO.getUsername(), resetPasswordVO.getVerifyCode(), resetPasswordVO.getPassword());
    }
}
